#FILE: EducationRegistryParser.py
#DESC: Parses ustav informacii a prognoz skolstva (uips) content

from web.service.LBCParser import LBCParser
from geo.models import NoSuchCity, NoSuchStreet, NoSuchLocation
from infra.logging import logger


class UipsParser(LBCParser):

	def __init__(self, lbcategory, dataProcessor): 
		LBCParser.__init__(self, lbcategory, dataProcessor)
		
		self.orgName_ = None
		self.email_ = None
		self.url_ = None
		
		self.fieldIdx_ = 0
		
		log = logger.getLogger()
		log.debug("%s = %s" % (self, self.__dict__))


	def reset__(self):
		self.fieldIdx_ = 1
		self.orgName_ = None
		self.email_ = None
		self.url_ = None
		
		LBCParser.reset__(self)


	def start_td(self, attrs):
		log = logger.getLogger()
		
		if self.fieldIdx_ == 5:		
			try:
				if len(self.errors_) == 0:
					self.createOrganization(name = self.orgName_, \
								            url = self.url_, \
											email = self.email_)
			except NoSuchLocation, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)
			except Exception, e:
				log.error('An exception caught, reason: %s' % e)					
			
			self.reset__()
			
		else:
			self.fieldIdx_ += 1


	def do_handle_data(self, data):
		log = logger.getLogger()
		
		if self.fieldIdx_ == 1:
			self.orgName_ = data
		if self.fieldIdx_ == 2:
			try:
				self.setCity(data)
			except NoSuchCity, e:
				log.error('NoSuchCity exception caught, reason: %s' % e)		
		if self.fieldIdx_ == 3:		
			try:
				if len(self.errors_) == 0:
					self.setStreet(data)
			except NoSuchStreet, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)
		if self.fieldIdx_ == 4:		
			self.email_ = data
		if self.fieldIdx_ == 5:
			self.url_ = self.dataProcessor_.getUrl(data)		


	def getId(self):
		return self.__class__.__name__
